import React, { Component, Fragment } from 'react';

import { Button, Card, message, Modal, Space, Table } from 'antd';

import { timeFormat } from '../../utils/toolKit';
import LinkButton from '../../components/LinkButton';
import { reqUserList, reqDeleteUser, reqAddUser, reqUpdateUser } from '../../api';

import AddAndUpdate from './AddAndUpdate';

const TIMEFORMAT = 'yyyy-MM-dd hh:mm:ss';
/**
 * 用户管理
*/
export default class User extends Component {

    state = {
        users: [],
        loading: false,
        roles: [],
        visible: false,
        user: null
    }

    form = React.createRef()

    columns = [
        {
            title: '用户名',
            dataIndex: 'username'
        },
        {
            title: '邮箱',
            dataIndex: 'email'
        },
        {
            title: '电话',
            dataIndex: 'phone'
        },
        {
            title: '注册时间',
            dataIndex: 'create_time',
            render: record => timeFormat(record, TIMEFORMAT)
        },
        {
            title: '所属角色',
            dataIndex: 'role_id',
            render: role_id => {
                const { roles } = this.state;
                const res = roles.find(role => role._id === role_id)
                return res && res.name;
            }
        },
        {
            title: '操作',
            render: record => {
                return (
                    <Space>
                        <LinkButton onClick={() => this.handleUpdate(record)}>修改</LinkButton>
                        <LinkButton onClick={() => this.handleDelete(record)}>删除</LinkButton>
                    </Space>
                )
            }
        }
    ]

    handleUpdate(user) {
        this.setState({ user, visible: true }, () => {
            const form = this.form.current;
            form.setFieldsValue(user);
        });
    }

    handleDelete(user) {
        Modal.confirm({
            title: <Fragment>确认删除用户[{<LinkButton>{user.username}</LinkButton>}]吗？</Fragment>,
            onOk: async () => {
                const res = await reqDeleteUser(user._id);

                if (res.status === 0) {
                    message.success('删除用户成功');
                    const users = [...this.state.users];

                    users.splice(users.findIndex(item => item._id === user._id), 1);
                    this.setState({ users });
                    this.resetFormValue();
                } else {
                    message.error(res.msg);
                }
            }
        });
    }

    async getUserAndRole() {
        this.setState({ loading: true })

        const res = await reqUserList();

        if (res.status === 0) {

            this.setState({
                users: res.data.users,
                loading: false,
                roles: res.data.roles
            })
        } else {
            message.error(res.msg);
        }
    }

    showAddAndChange() {
        this.setState({ visible: true });
    }

    handleCancel() {
        this.resetFormValue();
        this.setState({ visible: false, user: null });
    }

    resetFormValue() {
        const form = this.form.current;
        form.setFieldsValue({
            create_time: null,
            email: '',
            password: '',
            phone: '',
            role_id: null,
            username: '',
            _id: '',
        });
    }

    handleAdd() {
        const form = this.form.current;

        form.validateFields()
            .then(async (vals) => {
                let res = null;
                const { user } = this.state;
                if (!user) {
                    res = await reqAddUser(vals);
                    if (res.status === 0) {
                        message.success('添加用户成功！');
                        const { data } = res;
                        const { users } = this.state;
                        this.setState({
                            users: [...users, data],
                            visible: false,
                            user: null
                        });
                        this.resetFormValue();
                    } else {
                        message.error(res.msg);
                    }
                } else {
                    vals = {
                        ...vals,
                        _id: user._id
                    }
                    res = await reqUpdateUser(vals);
                    if (res.status === 0) {
                        message.success('修改用户成功！');
                        const { data } = res;
                        const users = [...this.state.users];

                        users[users.findIndex(item => item._id === data._id)] = data;

                        this.setState({
                            users,
                            visible: false,
                            user: null
                        });
                        this.resetFormValue();
                    } else {
                        message.error(res.msg);
                    }
                }
            })
            .catch(() => { });
    }

    componentDidMount() {
        this.getUserAndRole();
    }

    render() {

        const { loading, users, visible, roles, user } = this.state;
        const { form, columns } = this;

        const title = (
            <Fragment>
                <Button type="primary" onClick={() => this.showAddAndChange()} >创建用户</Button>
                <Modal
                    title={user ? '修改用户' : '创建用户'}
                    visible={visible}
                    onCancel={() => this.handleCancel()}
                    onOk={() => this.handleAdd()}
                >
                    <AddAndUpdate form={form} roles={roles} user={user || {}} />
                </Modal>
            </Fragment>
        )

        return (
            <Card title={title}>
                <Table
                    columns={columns}
                    dataSource={users}
                    rowKey="_id"
                    bordered
                    loading={loading}
                    scroll={{ y: 450 }}
                >
                </Table>
            </Card>
        )
    }
}
